package com.example.recipesapp.ui.viewmodel

import android.app.Application
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import androidx.room.Room
import com.example.recipesapp.data.AppDatabase
import com.example.recipesapp.data.Recipe
import com.example.recipesapp.data.Step
import com.example.recipesapp.repository.RecipeRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class RecipeViewModel(application: Application) : AndroidViewModel(application) {
    private val repository: RecipeRepository
    private val _searchQuery = mutableStateOf("")
    private val searchQuery: String get() = _searchQuery.value

    val searchResults = mutableStateListOf<Recipe>()
    var selectedRecipe by mutableStateOf<Recipe?>(null)
    val steps = mutableStateListOf<Step>()

    init {
        val db = Room.databaseBuilder(application, AppDatabase::class.java, "recipes.db").build()
        repository = RecipeRepository(db.recipeDao())
    }

    fun search() {
        viewModelScope.launch(Dispatchers.IO) {
            searchResults.clear()
            if (searchQuery.isNotEmpty()) {
                searchResults.addAll(repository.searchRecipes(searchQuery))
            }
        }
    }

    fun loadSteps(recipeId: Long) {
        viewModelScope.launch(Dispatchers.IO) {
            steps.clear()
            steps.addAll(repository.getSteps(recipeId))
        }
    }

    fun updateSearchQuery(query: String) {
        _searchQuery.value = query
    }

    fun getSuggestions(query: String): List<String> {
        return  if (query.isNotEmpty()) emptyList()
            else listOf("${query}食谱", "快速${query}", "健康${query}")

    }
}